//
//  YMZIP.swift
//  swift_review
//
//  Created by Andrew on 2024/12/9.
//

import UIKit
import ZIPFoundation

class YMZIP: NSObject {

    func compressFilesToZip(files: [URL], outputZipURL: URL) throws {
        // 创建一个空的 ZIP 文件
        let fileManager = FileManager.default
        if fileManager.fileExists(atPath: outputZipURL.path) {
            try fileManager.removeItem(at: outputZipURL) // 如果文件已存在，先删除
        }
        fileManager.createFile(atPath: outputZipURL.path, contents: nil, attributes: nil)

        // 创建 ZIP 存档
        do {
            let archive = try Archive(url: outputZipURL, accessMode: .create)
            // 添加文件到 ZIP
            // try archive.addEntry(with: ...)
            // 添加文件到 ZIP
            for fileURL in files {
                let fileName = fileURL.lastPathComponent
                try archive.addEntry(
                    with: fileName,
                    relativeTo: fileURL.deletingLastPathComponent(),
                    compressionMethod: .deflate
                )
            }
            print("压缩成功，ZIP 文件路径：\(outputZipURL.path)")
        } catch {
            // 处理创建 ZIP 时的错误
            print("Error creating ZIP archive: \(error)")
        }
    }

    func tryUse() {
        // 示例调用
        do {
            let file1 = URL(fileURLWithPath: "/path/to/video.mp4")
            let file2 = URL(fileURLWithPath: "/path/to/image.jpg")
            let outputZipURL = URL(fileURLWithPath: "/path/to/output.zip")
            try compressFilesToZip(files: [file1, file2], outputZipURL: outputZipURL)
        } catch {
            print("压缩失败：\(error)")
        }
    }
}
